import { useCallback, useEffect, useRef, useState } from "react";
import { rotateChange } from "../utils/viewHelp";
import { Axis } from "../utils/constant";
import React from "react";
interface Position {
  x: number;
  y: number;
}

export const Knob = (Props: { axis: Axis; }) => {
  const [hasMouseDown, setHasMouseDown] = useState<boolean>(false);
  const [centerPos, setCenterPos] = useState<Position>({ x: 0, y: 0 });
  const [mousePosition, setMousePosition] = useState<Position>({ x: 0, y: 0 });
  const [rotateDegree, setRotateDegree] = useState<number>(0);
  const [axisName, setaxisName] = useState<string>();
  const domRef = useRef<HTMLDivElement>(null);

  const getAxisName = useCallback(() => {
    switch (Props.axis) {
      case Axis.x:
        setaxisName('X');
        break;
      case Axis.y:
        setaxisName('Y');
        break;
      case Axis.z:
        setaxisName('Z');
        break;
    }
  },[Props.axis])

  useEffect(() => {
    getAxisName();
    const handleMouseMove = (event: { clientX: number; clientY: number; }) => {
      setMousePosition({ x: event.clientX, y: event.clientY });
    };

    const handleMouseUp = () => {
      setHasMouseDown(false);
    }

    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);

    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
    };
  }, [getAxisName, mousePosition, hasMouseDown]);

  useEffect(() => {
    if (!hasMouseDown) return;
    const positionOffsetX = mousePosition.x - centerPos.x;
    const positionOffsetY = mousePosition.y - centerPos.y;
    const rotateAngle = Math.floor((Math.atan2(positionOffsetY, positionOffsetX) * 180) / Math.PI) + 180;
    setRotateDegree(rotateAngle);
  }, [centerPos.x, centerPos.y, hasMouseDown, mousePosition]);

  useEffect(() => {
    rotateChange(rotateDegree, Props.axis)
  }, [Props.axis, rotateDegree])

  const handleMouseDown = () => {
    if (!domRef.current) return;
    setHasMouseDown(true);
    const { left, width, top, height } = domRef.current.getBoundingClientRect();
    setCenterPos({ x: left + width / 2, y: top + height / 2 });
  };

  return (
    <div className="flex flex-col justify-center items-center pt-3">
      <div
        ref={domRef}
        className="bg-black h-10 w-10 rounded-full flex justify-center items-center"
        onMouseDown={handleMouseDown}
      >
        <div
          className="h-2 w-20"
          style={{ transform: `rotate(${rotateDegree}deg)` }}
        >
          <div className="bg-white h-2 w-2 rounded-full"></div>
        </div>
      </div>
      <div className="flex justify-center">{axisName}轴 : {rotateDegree}度</div>
    </div>
  );

};

export default React.memo(Knob); 
